import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login.vue'
import NoPermission from '@/views/NoPermission.vue'
Vue.use(Router);

// Fixed NavigationDuplicated Problem -- 修正了导航重复问题
const originalPush = Router.prototype.push;
/**
 * 重写push
 * @param {string | Location} location 
 * @param {Function} onComplete 
 * @param {ErrorHandler} onAbort 
 */
Router.prototype.push = function push(location, onComplete, onAbort) {
    if (onComplete || onAbort) return originalPush.call(this, location, onComplete, onAbort)
    return originalPush.call(this, location).catch(err => err)
}

const createRouter = () =>
    new Router({
        mode: 'history',
        scrollBehavior: () => ({
            y: 0
        }),
        routes: [{
                path: '/',
                redirect: '/system/role'
            },
            {
                path: '/noPermission',
                component: NoPermission
            },
            {
                path: '/login',
                component: Login
            },
            // 尾部多加一个空花括号报错: [vue-router] "path" is required in a route configuration.
        ]
    })

const router = createRouter();

router.onError((err) => {
    /*
    1. 错误在一个路由守卫函数中被同步抛出；
    2. 错误在一个路由守卫函数中通过调用 next(err) 的方式异步捕获并处理；
    3. 渲染一个路由的过程中，需要尝试解析一个异步组件时发生错误。
    */
    console.log(err)
})

/**
 * 通过更新matcher来实现addRoutes的更新
 */
export function resetRouter() {
    const newRouter = createRouter();
    // matcher: {match: ƒ, addRoutes: ƒ}
    router.matcher = newRouter.matcher // reset router
}
export default router

/*
webpack之前不支持动态编译，所以很多项目都在路由表维护了一份映射表如下：
const routerMap = {
    user: () => import('/views/user'),
    role: () => import('/views/role'),
    ...
}
*/